<template>
	<view>
		<view class="check-view-box">
			<view class="roc-btn">
				<text @click="isChart = !isChart">切换</text>
			</view>
		</view>
		<view class="chartTitle">
			<u-divider :text="title" textSize="30" textColor="#3c9cff"></u-divider>
		</view>
		<view class="" v-show="isChart">
			<publicTabel ref="data" />
		</view>
		<view class="" v-show="!isChart">
			<view class="charts-box">
				<qiun-data-charts :type="chartType" :chartData="chartData" :opts="opts" />
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getChartDetail,
		getChartData
	} from '@/api/report.js';
	import publicTabel from '@/components/publicTabel.vue'
	import newValueShowName from '@/mixins/valueShowName.js'
	export default {
		components: {
			publicTabel,
		},
		mixins: [newValueShowName],
		data() {
			return {
				title: '',
				data: {},
				isChart: false,
				tableData: {
					headers: [],
					list: []
				},
				chartType: 'column',
				opts: {},
				chartData: {
					categories: [],
					series: []
				},
				detailData: {},
				chartsData: {}
			}
		},
		onLoad(option) {
			this.data = option;
		},
		mounted() {
			this.fetchData();
		},
		methods: {
			async fetchData() {
				// 详情（图表配置json）
				const {
					data: dataList
				} = await getChartDetail({
					id: this.data.reportId,
				})
				this.title = dataList.data.name
				this.detailData = dataList.data
				if (!this.detailData) return
				// console.log(this.detailData)
				this.detailData.config_json = JSON.parse(this.detailData.config_json)
				let headers = this.detailData.config_json
				// 表头(字段)处理
				headers = this.detailData.config_json.filter((fieldObj) => {
					return fieldObj.isShow == true
				})
				let arr = []
				headers.forEach(ele => {
					let obj = {
						label: ele.name,
						key: ele.field
					}
					arr.push(obj)
				})
				this.tableData.headers = arr
				// 数据
				const {
					data
				} = await getChartData({
					id: this.data.reportId,
				})
				// 使用mixin方法（转换数据格式）
				this.tableData.list = await this.getChartTableApiData(
					this.detailData.config_json,
					data.data,
					true
				)
				let datas = {
					headers: headers,
					list: this.tableData.list
				}
				this.spellChartData()
				this.dataHandle(datas)
			},
			//图表数据组装
			spellChartData() {
				//图表类型
				const chart_type = this.detailData.chart_type
				if (chart_type === 'bar') {
					this.chartType = 'column'
					let obj = {
						color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
							"#ea7ccc"
						],
						padding: [15, 15, 0, 5],
						legend: {},
						xAxis: {
							disableGrid: true
						},
						yAxis: {
							data: [{
								min: 0
							}]
						},
						extra: {
							column: {
								type: "group",
								width: 30,
								activeBgColor: "#000000",
								activeBgOpacity: 0.08
							}
						}
					}
					this.opts = obj
				} else if (chart_type === 'line') {
					this.chartType = this.detailData.chart_type
					let obj = {
						padding: [20, 0, 0, 0],
						xAxis: {
							disableGrid: true,
							rotateLabel: true,
						},
						yAxis: {
							showTitle: true,
							data: [{
								type: "value",
								position: "left",
								disabled: false,
								axisLine: true,
								axisLineColor: "#CCCCCC",
								calibration: false,
								fontColor: "#666666",
								fontSize: 13,
								textAlign: "right",
								title: "单位：吨",
								titleFontSize: 13,
								titleOffsetY: -10,
								titleOffsetX: 0,
								titleFontColor: "#666666",
							}]
						},
						legend: {
							padding: 20,
						},
						dataPointShape: false,
						extra: {
							line: {
								type: "curve",
								width: 2
							}
						}
					}
					this.opts = obj
				} else if (chart_type === 'pie') {
					this.chartType = this.detailData.chart_type
					let obj = {
						color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
							"#ea7ccc"
						],
						padding: [5, 5, 5, 5],
						extra: {
							pie: {
								activeOpacity: 0.5,
								activeRadius: 10,
								offsetAngle: 0,
								labelWidth: 15,
								border: false,
								borderWidth: 3,
								borderColor: "#FFFFFF"
							}
						}
					}
					this.opts = obj
				}
				this.oddChart()
			},
			//单图表
			oddChart() {
				if (this.detailData.chart_type === 'pie') {
					// y轴数据   勾选了y的字段数组
					const yFieldObjList = this.detailData.config_json.filter((item) => {
						return item.y == true
					})
					let pieChartObj = {
						data: []
					}
					console.log(yFieldObjList)
					yFieldObjList.forEach((item) => {
						// 饼图展示总计
						const allValue = this.tableData.list
							.map((dataItem) => {
								return dataItem[item.field]
							})
							.reduce((preVal, nextVal) => {
								if (isNaN(nextVal)) {
									nextVal = 0
								}
								return preVal + Number(nextVal)
							}, 0)
						pieChartObj.data.push({
							name: item.name,
							value: allValue,
						})
					})
					let series = []
					series.push(pieChartObj)
					this.chartData.series = series
				} else {
					// 勾选了x的字段数组
					const xFieldList = this.detailData.config_json
						.filter((item) => {
							return item.x == true
						})
						.map((item) => {
							return item.field
						})
					// x轴数据
					this.chartData.categories = this.tableData.list.map((dataItem) => {
						let xAxisItem = ''
						for (let i = 0; i < xFieldList.length; i++) {
							xAxisItem += `${dataItem[xFieldList[i]]} `
						}
						return xAxisItem
					})
					// y轴数据   勾选了y的字段数组
					const yFieldObjList = this.detailData.config_json.filter((item) => {
						return item.y == true
					})
					// y轴数据组织
					const yAxisObjList = []
					yFieldObjList.forEach((item) => {
						// 指示器展示 单位存储
						this.opts.yAxis.data[0].title = `单位:${item.company}`
						const chartObj = {
							name: item.name,
							data: [],
						}
						chartObj.data = this.tableData.list.map((dataItem) => {
							return dataItem[item.field]
						})
						yAxisObjList.push(chartObj)
					})
					this.chartData.series = yAxisObjList
				}
			},
			dataHandle(tableData) {
				let arr = []
				tableData.headers.forEach((ele) => {
					if (ele.sum) {
						let bit = 0;
						if (ele.bit) {
							bit = ele.bit
						}
						let sum = (tableData.list
								.reduce((c, item) => c + item[ele.field] * 1, 0))
							.toFixed(bit)
						let obj = {
							[ele.field]: `总：${sum}${ele.company}`,
							key: ele.field,
						}
						arr.push(obj)
					}
				})
				let list = this.tableData.list
				if (arr.length > 0) {
					let sum = {}
					arr.forEach((item) => {
						sum[item.key] = item[item.key]
					})
					list.push(sum)
				}
				let obj = {
					headers: this.tableData.headers,
					list: list
				}
				this.$refs['data'].showEdit(obj)
			},
		}
	}
</script>

<style lang="scss" scoped>
	/*样式的width和height一定要与定义的cWidth和cHeight相对应*/
	.Scroll {
		transform: rotate(90deg);
		height: 100vw;
		width: 100vh;
		transform-origin: 0% 100%;
		top: -100vw;
		position: relative;
	}

	.charts-box {
		width: 100%;
		min-height: 300px;
	}

	.check-view-box {
		position: fixed;
		right: 22rpx;
		bottom: 224rpx;
		z-index: 99;
		opacity: 0.8;

		.roc-btn {
			width: 80rpx;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			color: #fff;
			padding: 0;
			border-radius: 50%;
			background-color: rgb(60, 156, 255);
		}
	}
</style>
